/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-12
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-16
 * @Description: 
 */
import 'package:chat_client/models/user_model.dart';
import 'package:chat_client/utils/date_formater.dart' show getTimestamp;
import 'package:hive/hive.dart';

import 'hive_repository.dart';

/// 认证信息本地读写
class AuthRepository {
  // 单例
  AuthRepository._internal();
  static final AuthRepository _instance = AuthRepository._internal();
  static AuthRepository get instance => _instance;

  // 打开数据库
  final HiveService hive = HiveService.instance;
  late final Box<dynamic> _selfBox;
  init() async {
    _selfBox = await hive.openBox<dynamic>('self');
  }

  // accessToken
  String? get accessToken => _selfBox.get('accessToken');

  // refreshToken
  String? get refreshToken => _selfBox.get('refreshToken');

  // 是否已经将远程数据初始化到本地
  bool? get isInitLocalStore => _selfBox.get('isLocalStore');

  User? get userSelf => _selfBox.get('user');

  String get userSelfId => userSelf?.userId ?? '';

  // 储存token
  Future<void> setToken(
      {String? accessToken, String? refreshToken, int? expired}) async {
    await _selfBox.put('accessToken', accessToken);
    await _selfBox.put('expired', expired);
    await _selfBox.put('refreshToken', refreshToken);
  }

  Future<void> celarTokens() async {
    await _selfBox.delete('accessToken');
    await _selfBox.delete('expired');
    await _selfBox.delete('refreshToken');
  }

  // 检查过期时间
  bool shouldRefreshToken() {
    final int? expired = _selfBox.get('expired');
    if (expired == null) return true;
    final time = getTimestamp();
    // 离过期时间还有多久
    if (expired - time < 1000 * 60 * 5) return true;

    return false;
  }

  // 设置储存标志
  Future<void> setLocalStore(bool isLocalStore) async {
    await _selfBox.put('isLocalStore', isLocalStore);
  }

  /// 用户部分

  // 储存用户信息
  Future<bool> setUser(user) async {
    await _selfBox.put('user', user);
    return true;
  }

  // 清除用户信息
  Future<void> deleteUser() async {
    await _selfBox.delete('user');
  }

  // 修改用户信息
  Future<void> updateUser(Map<String, dynamic> updatedFields) async {
    final user = userSelf;
    final newUser = user!.copyWith(updatedFields);
    await setUser(newUser);
  }
}
